// pages/bargainItem/bargainItem.js
const app = getApp();
let utils = require('../../utils/util.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    scrollHeight: 0,        //"滚动视图的高度"
    topIcon:'../../images/bargain/bread.jpg',
    leftTimeStr:[],
    leftTime:0,
    discountPrice:12,
    originalPrice:36,
    goodName:'芝心大咖',
    stockNum:69,
    indate:'2018-05-30 18:40:00',
    itemId:'123',
    state:'0',      //0表示活动进行中 1表示该砍价已经结束
    intervalId: -1000,           //倒计时计时器id
  },
  addInterval() {                           //添加计时器
    if (this.data.intervalId != -1000) return;
    this.data.intervalId = setInterval(this.intervalHandle, 1000);
  },
  intervalHandle() {                        //计时器处理
    this.data.leftTime--;
    if (this.data.leftTime <= 0) {
      this.timeOutHandle();
    }
    this.refreshExistingTime();
  },
  timeOutHandle() {                //砍价活动时间到了
    this.removeInterval();
    this.setData({ state:'1'});
    console.log('砍价活动时间到了');
  },
  removeInterval() {                     //移除计时器
    if (this.data.intervalId == -1000) return;
    clearInterval(this.data.intervalId);
    this.data.intervalId = -1000;
  },
  refreshExistingTime() {          //刷新倒计时
    let timeChar = utils.secToTime(this.data.leftTime);
    this.setData({ leftTimeStr: timeChar.split(':') });
  },
  //返回到首页
  toIndex() {
    wx.switchTab({ url: '../index/index' });
  },
  // 发起砍价
  callBargain(){
    console.log('发起砍价');
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.leftTime=12345;
    let timestamp=123456;
    this.setData({ indate: utils.formatTime(new Date(parseInt(timestamp)),'-')});
    this.refreshExistingTime();
    this.addInterval();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var query = wx.createSelectorQuery();
    query.select('#bargain-item-bottom').boundingClientRect();
    wx.getSystemInfo({
      success: win_res => {
        //获取滚动条的高度
        query.exec(dom_res => {
          if (!dom_res[0]) this.setData({ scrollHeight: win_res.windowHeight });
          else {
            let bottom_h = dom_res[0].height;
            this.setData({ scrollHeight: win_res.windowHeight - bottom_h });
          }
        })
      }
    });
  },

  onShow: function () {

  },
  onHide: function () {

  },
  onUnload: function () {
    this.removeInterval();
    console.log('bargainItem界面onUnload....');
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: "限时团购,等你加入~"
    };
    shareObj.path = '/pages/bargainItem/bargainItem?id=' + this.data.itemId;
    //shareObj.imageUrl = this.data.topIcon;
    return shareObj;
  }
})
